<template>
  <el-dialog @close="reset" fullscreen title="新增" :visible.sync="info.isShow">
    <el-form
      ref="goodsForm"
      label-width="80px"
      :model="goodsData"
      :rules="rules"
    >
      <el-tabs v-model="activePane">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select
              @change="firstCateChange"
              placeholder="一级分类"
              v-model="goodsData.first_cateid"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select placeholder="二级分类" v-model="goodsData.second_cateid">
              <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsname">
            <el-input
              placeholder="商品名称"
              v-model="goodsData.goodsname"
            ></el-input>
          </el-form-item>
          <el-form-item label="零售价格" prop="price">
            <el-input
              placeholder="零售价格"
              v-model="goodsData.price"
            ></el-input>
          </el-form-item>
          <el-form-item label="市场价格" prop="market_price">
            <el-input
              placeholder="市场价格"
              v-model="goodsData.market_price"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              list-type="picture-card"
              action="#"
              :auto-upload="false"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="imgChange"
              ref="upload"
              :file-list="imgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品规格" prop="specsid">
            <el-select
              @change="specsChange"
              placeholder="商品规格"
              v-model="goodsData.specsid"
            >
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :value="item.id"
                :label="item.specsname"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规格属性" prop="specsattr">
            <!-- multiple: 实现多选 -->
            <el-select
              multiple
              placeholder="规格属性"
              v-model="goodsData.specsattr"
            >
              <el-option
                v-for="(item, index) in specsAttr"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否新品" prop="isnew">
            <el-switch
              v-model="goodsData.isnew"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item label="是否热卖" prop="ishot">
            <el-switch
              v-model="goodsData.ishot"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="goodsData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品介绍" name="second">
          <el-form-item prop="description" label-width="0">
            <Wangeditor
              ref="description"
              style="margin-bottom: 20px;height:330px"
              id="description"
              width="100%"
              height="300"
              v-model="goodsData.description"
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
const defaultData = {
  first_cateid: "", // 一级分类id
  second_cateid: "", //二级分类id
  goodsname: "", // 商品名称
  price: "", //商品价格
  market_price: "", // 市场价格
  isnew: "", // 是否新品
  ishot: "", // 是否热卖
  status: "", // 商品状态
  specsid: "", // 商品规格
  specsattr: [], // 商品规格属性
  img: null, // 商品图片
  description: "", // 商品介绍
};
// 导入vue-wangwditor
import Wangeditor from "vue-wangeditor";
// 导入vuex辅助函数
import { mapState, mapActions } from "vuex";
export default {
  components: { Wangeditor },
  computed: {
    ...mapState("cate", ["cateList"]),
    ...mapState("specs", ["specsList"]),
  },
  props: ["info"],
  data() {
    // 自定义表单校验函数
    const validDesc = (rule, value, callback) => {
      // 获取富文本编辑器的内容
      const description = this.$refs.description.getHtml();
      if (description === "<p><br></p>") {
        this.$message.error("请输入商品介绍");
        return callback(new Error("请输入商品介绍"));
      }
      callback();
    };
    return {
      activePane: "first",
      // 图片上传组件默认需要展示的图片列表
      imgList: [],
      // 二级分类
      secondCateList: [],
      // 规格属性
      specsAttr: [],
      // 表单数据
      goodsData: { ...defaultData },
      //  表单校验规则
      rules: {
        first_cateid: { required: true, message: "请选择", trigger: "blur" },
        second_cateid: { required: true, message: "请选择", trigger: "blur" },
        goodsname: { required: true, message: "请输入", trigger: "blur" },
        price: { required: true, message: "请输入", trigger: "blur" },
        market_price: { required: true, message: "请输入", trigger: "blur" },
        isnew: { required: true, message: "请选择", trigger: "blur" },
        ishot: { required: true, message: "请选择", trigger: "blur" },
        status: { required: true, message: "请选择", trigger: "blur" },
        specsid: { required: true, message: "请选择", trigger: "blur" },
        specsattr: { required: true, message: "请选择", trigger: "blur" },
        description: { validator: validDesc, trigger: "blur" },
      },
    };
  },
  methods: {
    ...mapActions("cate", ["getCateListAction"]),
    ...mapActions("specs", ["getSpecsListAction"]),
    // 更新表单数据
    setFormData(obj) {
      // 剔除多余的属性
      delete obj.firstcatename;
      delete obj.secondcatename;

      this.goodsData = { ...obj };
      this.goodsData.specsattr=obj.specsattr.split(',');
      // 手动设置图片上传组件需要展示的默认图片
      this.imgList = [{ url: this.$baseUrl + obj.img }];
      // 手动设置富文本编辑的内容
      setTimeout(() => {
        this.$refs.description.setHtml(obj.description);
      }, 200);
      // 根据一级分类id更新二级分类信息
      this.firstCateChange(obj.first_cateid,false);
      // 更新商品规格属性数组specsAttr
      this.specsAttr=obj.specsattr.split(',');
    },
    reset() {
      // 重置表单数据
      this.goodsData = { ...defaultData,id:0 };
      // 管理对话框组件
      this.info.isShow = false;
      //  手动重置富文本编辑器的内容
      this.$refs.description.setHtml("");
      // 清空图片上传组件中用户已经选择的图片信息
      this.$refs.upload.clearFiles();
    },
    // 提交表单
    submit() {
      this.$refs.goodsForm.validate((valid) => {
        if (valid) {
          // this.goodsData=> FormData
          // 发送数据请求
          const fd = new FormData();
          for (let key in this.goodsData) {
            fd.append(key, this.goodsData[key]);
          }
          const url=this.goodsData.id>0?'/goodsedit':'/goodsadd';
          this.$axios.post(url, fd).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              // 更新商品数据 : 通知父组件实现数据更新
              this.$emit("updateGoods");
              // 重置数据
              this.reset();
            } else {
              this.$message.error(res.msg);
            }
          });
        } 
      });
    },
    // 监听用户选择图片
    imgChange(file) {
      // 手动同步用户选择的图片
      this.goodsData.img = file.raw;
    },
    // 规格下拉框change事件处理函数
    specsChange(id) {
      // 根据id查找索引
      const index = this.specsList.findIndex((item) => item.id === id);
      // 清空之前选择的规格属性
      this.goodsData.specsattr = [];
      // 更新规格属性
      this.specsAttr = this.specsList[index].attrs;
    },
    // 一级分类下拉框change事件处理函数
    firstCateChange(id,flag=true) {
      // 根据id查找索引
      const index = this.cateList.findIndex((item) => item.id === id);
      // 更新二级分类
      // 通过鼠标点击一级分类下拉框的时候, 需要清空second_cateid, 点击编辑按钮展示商品默认信息的时候, 不需要清空second_cateid
      if(flag){
        this.goodsData.second_cateid = '';
      }
      this.secondCateList = this.cateList[index].children
        ? this.cateList[index].children
        : [];
    },
    // 商品图片超过上限的提示
    limitTips() {
      this.$message.warning("此处只能选择一张图片");
    },
  },
  created() {
    //  请求商品分类
    this.getCateListAction();
    //  请求商品规格
    this.getSpecsListAction({ page: 1, size: 100 });
  },
};
</script>

<style>
</style>